package com.waikuai.shop.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.waikuai.shop.common.result.Result;
import com.waikuai.shop.dto.EmployeeFormDTO;
import com.waikuai.shop.dto.EmployeeQueryDTO;
import com.waikuai.shop.service.UserService;
import com.waikuai.shop.vo.EmployeeVO;
import com.waikuai.shop.vo.ImportResultVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;

/**
 * 员工管理控制器
 * @author waikuai
 */
@Slf4j
@RestController
@RequestMapping("/employees")
@RequiredArgsConstructor
@Validated
public class EmployeeController {

    private final UserService userService;

    /**
     * 分页查询员工列表
     */
    @GetMapping("/page")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<IPage<EmployeeVO>> getEmployeePage(@Valid EmployeeQueryDTO queryDTO) {
        log.info("分页查询员工列表: {}", queryDTO);
        
        try {
            IPage<EmployeeVO> page = userService.getEmployeePage(queryDTO);
            return Result.success("查询成功", page);
        } catch (Exception e) {
            log.error("查询员工列表失败: {}", e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    /**
     * 根据ID获取员工详情
     */
    @GetMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<EmployeeVO> getEmployeeById(@PathVariable Long id) {
        log.info("获取员工详情: id={}", id);
        
        try {
            EmployeeVO employee = userService.getEmployeeById(id);
            if (employee == null) {
                return Result.error("员工不存在");
            }
            return Result.success("查询成功", employee);
        } catch (Exception e) {
            log.error("获取员工详情失败: {}", e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    /**
     * 新增员工
     */
    @PostMapping
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> addEmployee(@Validated @RequestBody EmployeeFormDTO formDTO) {
        log.info("新增员工: {}", formDTO.getUsername());
        
        try {
            userService.addEmployee(formDTO);
            return Result.success("添加成功");
        } catch (Exception e) {
            log.error("新增员工失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新员工信息
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> updateEmployee(@PathVariable Long id, @Validated @RequestBody EmployeeFormDTO formDTO) {
        log.info("更新员工信息: id={}", id);
        
        try {
            formDTO.setId(id);
            userService.updateEmployee(formDTO);
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新员工信息失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 删除员工（逻辑删除）
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> deleteEmployee(@PathVariable Long id) {
        log.info("删除员工: id={}", id);
        
        try {
            userService.deleteEmployee(id);
            return Result.success("删除成功");
        } catch (Exception e) {
            log.error("删除员工失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量删除员工
     */
    @DeleteMapping("/batch")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> batchDeleteEmployees(@RequestBody List<Long> ids) {
        log.info("批量删除员工: ids={}", ids);
        
        try {
            userService.batchDeleteEmployees(ids);
            return Result.success("批量删除成功");
        } catch (Exception e) {
            log.error("批量删除员工失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 启用员工账号
     */
    @PutMapping("/{id}/enable")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> enableEmployee(@PathVariable Long id) {
        log.info("启用员工账号: id={}", id);
        
        try {
            userService.updateEmployeeStatus(id, 1);
            return Result.success("启用成功");
        } catch (Exception e) {
            log.error("启用员工账号失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 禁用员工账号
     */
    @PutMapping("/{id}/disable")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> disableEmployee(@PathVariable Long id) {
        log.info("禁用员工账号: id={}", id);
        
        try {
            userService.updateEmployeeStatus(id, 0);
            return Result.success("禁用成功");
        } catch (Exception e) {
            log.error("禁用员工账号失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量启用员工账号
     */
    @PutMapping("/batch/enable")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> batchEnableEmployees(@RequestBody List<Long> ids) {
        log.info("批量启用员工账号: ids={}", ids);
        
        try {
            userService.batchUpdateEmployeeStatus(ids, 1);
            return Result.success("批量启用成功");
        } catch (Exception e) {
            log.error("批量启用员工账号失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量禁用员工账号
     */
    @PutMapping("/batch/disable")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> batchDisableEmployees(@RequestBody List<Long> ids) {
        log.info("批量禁用员工账号: ids={}", ids);
        
        try {
            userService.batchUpdateEmployeeStatus(ids, 0);
            return Result.success("批量禁用成功");
        } catch (Exception e) {
            log.error("批量禁用员工账号失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 重置员工密码
     */
    @PutMapping("/{id}/reset-password")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<String> resetPassword(@PathVariable Long id) {
        log.info("重置员工密码: id={}", id);
        
        try {
            String newPassword = userService.resetEmployeePassword(id);
            return Result.success("重置成功，新密码为：" + newPassword);
        } catch (Exception e) {
            log.error("重置员工密码失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取所有部门列表（用于筛选下拉框）
     */
    @GetMapping("/departments")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<List<String>> getAllDepartments() {
        log.info("获取所有部门列表");
        
        try {
            List<String> departments = userService.getAllDepartments();
            return Result.success("查询成功", departments);
        } catch (Exception e) {
            log.error("获取部门列表失败: {}", e.getMessage(), e);
            return Result.error("查询失败");
        }
    }

    /**
     * 导入员工Excel
     */
    @PostMapping("/import")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public Result<ImportResultVO> importEmployees(@RequestParam("file") MultipartFile file) {
        log.info("导入员工Excel文件");
        
        try {
            ImportResultVO result = userService.importEmployees(file);
            return Result.success("导入完成", result);
        } catch (Exception e) {
            log.error("导入员工Excel失败: {}", e.getMessage(), e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 下载Excel模板
     */
    @GetMapping("/download-template")
    public void downloadTemplate(HttpServletResponse response) {
        log.info("下载Excel模板");
        
        userService.downloadTemplate(response);
    }

    /**
     * 导出员工数据到Excel
     */
    @GetMapping("/export")
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    public void exportEmployees(EmployeeQueryDTO queryDTO, HttpServletResponse response) {
        log.info("导出员工数据: {}", queryDTO);
        
        userService.exportEmployees(queryDTO, response);
    }
}

